const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');

console.log('🔍 开始加载地址路由...');

// 首先检查控制器
let addressController;
try {
  addressController = require('../controllers/addressController');
  console.log('✅ 地址控制器加载成功，方法:', Object.keys(addressController));
} catch (error) {
  console.error('❌ 地址控制器加载失败:', error.message);
  // 创建简单的回退控制器
  addressController = {
    getUserAddresses: (req, res) => res.json({ success: true, data: [], message: '地址功能开发中' }),
    getDefaultAddress: (req, res) => res.json({ success: true, data: null, message: '地址功能开发中' }),
    createAddress: (req, res) => res.json({ success: true, message: '地址功能开发中' }),
    updateAddress: (req, res) => res.json({ success: true, message: '地址功能开发中' }),
    deleteAddress: (req, res) => res.json({ success: true, message: '地址功能开发中' }),
    setDefaultAddress: (req, res) => res.json({ success: true, message: '地址功能开发中' })
  };
}

// 真实认证中间件
const authenticateToken = (req, res, next) => {
  console.log('🔐 开始用户认证验证...');
  
  // 从请求头获取 token
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
  
  if (!token) {
    console.log('❌ 未提供访问令牌');
    return res.status(401).json({
      success: false,
      message: '访问被拒绝，未提供认证令牌'
    });
  }
  
  try {
    // 验证 JWT token
    const JWT_SECRET = process.env.JWT_SECRET || 'your_jwt_secret_key_here';
    const decoded = jwt.verify(token, JWT_SECRET);
    
    // 将用户信息添加到请求对象
    req.user = {
      id: decoded.userId || decoded.id,
      phone: decoded.phone,
      name: decoded.name
    };
    
    console.log(`✅ 用户认证成功: ${req.user.name || '用户'} (ID: ${req.user.id})`);
    next();
  } catch (error) {
    console.error('❌ Token 验证失败:', error.message);
    
    if (error.name === 'TokenExpiredError') {
      return res.status(401).json({
        success: false,
        message: '令牌已过期，请重新登录'
      });
    }
    
    if (error.name === 'JsonWebTokenError') {
      return res.status(403).json({
        success: false,
        message: '无效的令牌'
      });
    }
    
    return res.status(500).json({
      success: false,
      message: '认证过程发生错误'
    });
  }
};

// 开发环境模拟认证
const devAuth = (req, res, next) => {
  // 如果是开发环境且提供了模拟用户头信息
  if (process.env.NODE_ENV === 'development' && req.headers['x-mock-user']) {
    console.log('🔐 使用开发环境模拟认证');
    try {
      const mockUser = JSON.parse(req.headers['x-mock-user']);
      req.user = {
        id: mockUser.id || 1,
        phone: mockUser.phone || '13800138000',
        name: mockUser.name || '测试用户'
      };
      console.log(`✅ 模拟用户: ${req.user.name} (ID: ${req.user.id})`);
      return next();
    } catch (error) {
      console.error('模拟用户头信息解析失败:', error);
    }
  }
  
  // 否则使用真实的 JWT 认证
  authenticateToken(req, res, next);
};

// 数据验证中间件
const validateAddress = (req, res, next) => {
  const { recipient, phone, province, city, district, detail } = req.body;
  
  const errors = [];
  
  if (!recipient || recipient.trim().length === 0) {
    errors.push('收货人姓名不能为空');
  }
  
  if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
    errors.push('手机号格式不正确');
  }
  
  if (!province || province.trim().length === 0) {
    errors.push('省份不能为空');
  }
  
  if (!city || city.trim().length === 0) {
    errors.push('城市不能为空');
  }
  
  if (!district || district.trim().length === 0) {
    errors.push('区县不能为空');
  }
  
  if (!detail || detail.trim().length === 0) {
    errors.push('详细地址不能为空');
  }
  
  if (errors.length > 0) {
    return res.status(400).json({
      success: false,
      message: '数据验证失败',
      errors
    });
  }
  
  next();
};

// 使用认证中间件
router.use(devAuth);

// 注册所有路由
router.get('/', addressController.getUserAddresses);
router.get('/default', addressController.getDefaultAddress);
router.post('/', validateAddress, addressController.createAddress);
router.put('/:id', validateAddress, addressController.updateAddress);
router.delete('/:id', addressController.deleteAddress);
router.patch('/:id/set-default', addressController.setDefaultAddress);

console.log('✅ 地址路由注册完成');

module.exports = router;